/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view.GUI;

import dao.Cliente.ClienteDao;
import dao.Cliente.ClienteDaoImpl;
import dao.Pedido.PedidoDao;
import java.awt.Point;
import java.util.ArrayList;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import pojo.Cliente;
import pojo.Pedido;

/**
 *
 * @author lg
 */
public class GUIListarClientes extends javax.swing.JInternalFrame {

    ClienteDao clientes;
    JTextField campoNomeCliente;
    JTable tabelaPedidos;
    PedidoDao pedidos;
    /**
     * Creates new form GUIListasClientes
     */
    public GUIListarClientes(ClienteDao clientes) {
        this.clientes = clientes;
        initComponents();
    }
    
    public GUIListarClientes(ClienteDao clientes,JTextField campoNomeCliente) {
        this.clientes = clientes;
        this.campoNomeCliente = campoNomeCliente;
        initComponents();
    }
    
    public GUIListarClientes(ClienteDao clientes,JTextField campoNomeCliente,
            JTable tabelaPedidos,PedidoDao pedidos) {
        this.clientes = clientes;
        this.pedidos = pedidos;
        this.campoNomeCliente = campoNomeCliente;
        this.tabelaPedidos = tabelaPedidos;
        initComponents();
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fieldNomeCliente = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(700, 600));

        jButton1.setText("Buscar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nome", "CPF", "Telefone", "Rua", "Cidade", "País", "Complemento", "Número", "CEP"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Long.class, java.lang.Long.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(fieldNomeCliente)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap())
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 401, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fieldNomeCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 317, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
        for (int x = dtm.getRowCount() - 1; x >= 0; x--) {
            dtm.removeRow(x);
        }
        if (fieldNomeCliente.getText() == null) {
        } else {
            Cliente cliente = new Cliente();
            cliente.setNome(fieldNomeCliente.getText());
            ArrayList<Cliente> clientesBuscados = (ArrayList<Cliente>) clientes.listarClientes();
            for (Cliente iteradorCliente : clientesBuscados) {
                if (iteradorCliente.getNome().contains(cliente.getNome())) {
                    dtm.addRow(new Object[]{
                        iteradorCliente.getNome(),
                        iteradorCliente.getCpf(),
                        iteradorCliente.getTelefone(),
                        iteradorCliente.getEndereco().getRua(),
                        iteradorCliente.getEndereco().getCidade(),
                        iteradorCliente.getEndereco().getPais(),
                        iteradorCliente.getEndereco().getComplemento(),
                        iteradorCliente.getEndereco().getNumero(),
                        iteradorCliente.getEndereco().getCep()
                        });
                }
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        if (evt.getClickCount() == 2) {
            Point p = evt.getPoint();
            int row = jTable1.rowAtPoint(p);
            int col = jTable1.columnAtPoint(p);
            //String stringTeste = String.format("row: %d    col: %d\n", row, col);
            //JOptionPane.showMessageDialog(null,stringTeste); 
            String nome = ((String) jTable1.getValueAt(row, 0));
            campoNomeCliente.setText(nome);
            campoNomeCliente.setEditable(false);
            if(tabelaPedidos != null){
                Cliente cliente = new Cliente();
                cliente.setNome(nome);
                cliente = clientes.buscarPorNome(cliente);
                ArrayList<Pedido> listaPedidos = (ArrayList) 
                        pedidos.buscarPorId((ArrayList<Long>) cliente.getPedidos());
                DefaultTableModel dtm = (DefaultTableModel) tabelaPedidos.getModel();
                for (Pedido listaPedido : listaPedidos) {
                    dtm.addRow(new Object[]{listaPedido.getId()});
                }
            }
            this.dispose();
        }
    }//GEN-LAST:event_jTable1MouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GUIListarClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GUIListarClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GUIListarClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUIListarClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField fieldNomeCliente;
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
